package com.czk.aop;

import com.alibaba.fastjson.JSON;
import com.czk.annotation.DoDoor;
import com.czk.config.StarterService;
import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/9 11:12
 */
@Aspect
@Component
public class DoJointPoint {
    @Autowired
    private StarterService starterService;
    /**
     * 日志
     */
    private static Logger LOGGER = LoggerFactory.getLogger(DoJointPoint.class);

    @Pointcut("@annotation(com.czk.annotation.DoDoor)")
    public void point() {

    }

    @Around("point()")
    public Object doRouter(ProceedingJoinPoint joinPoint) throws Throwable {
        // 拿到方法
        Method method = getMethod(joinPoint);
        // 拿到注解
        DoDoor annotation = method.getAnnotation(DoDoor.class);
        // 拿到值
        String keyValue = getFieldValue(annotation.key(), joinPoint.getArgs());
        // 日志
        LOGGER.info("door handler method：{} value：{}", method.getName(), keyValue);
        if (Objects.equals(null, keyValue) || Objects.equals("", keyValue)) {
            // 直接放行
            return joinPoint.proceed();
        }
        // 配置内容
        String[] split = starterService.split(",");
        for (String s : split) {
            if (Objects.equals(s, keyValue)) {
                // 放行
                return joinPoint.proceed();
            }
        }
        // 返回json
        return returnObject(annotation, method);
    }

    /**
     * 构建返回值
     *
     * @param annotation
     * @param method
     * @return
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    private Object returnObject(DoDoor annotation, Method method) throws IllegalAccessException, InstantiationException {
        // 拿到返回值类型
        Class<?> returnType = method.getReturnType();
        // 拿到返回值json
        String returnJson = annotation.returnJson();
        if (Objects.equals(returnJson, "")) {
            // 直接返回类型
            return returnType.newInstance();
        }
        // 返回json
        return JSON.parseObject(returnJson, returnType);
    }

    /**
     * 获取字段的属性值
     *
     * @param field
     * @param args
     * @return
     */
    private String getFieldValue(String field, Object[] args) {
        String fieldValue = null;
        for (Object arg : args) {
            try {
                if (fieldValue == null || Objects.equals("", fieldValue)) {
                    fieldValue = BeanUtils.getProperty(arg, field);
                } else {
                    break;
                }
            } catch (Exception e) {
                if (args.length == 1) {
                    return args[0].toString();
                }
            }
        }
        return fieldValue;
    }

    /**
     * 拿到方法
     *
     * @param joinPoint
     * @return
     * @throws NoSuchMethodException
     */
    private Method getMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        // 拿到签名
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        return joinPoint.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    }
}
